package com.caltco.cargo.ops.modules.sys.controller;

import com.caltco.cargo.ops.common.api.R2;
import com.caltco.cargo.ops.common.api.Result;
import com.caltco.cargo.ops.common.exception.RRException;
import com.caltco.cargo.ops.modules.sys.entity.TaskFile;
import com.caltco.cargo.ops.modules.sys.service.TaskFileService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController("taskFileController")
@RequestMapping("/api/file")
@Tag(name = "文件上传")
@AllArgsConstructor
public class TaskFileController {
    private final TaskFileService taskFileService;

    @RequestMapping(value = "batchUploadFile", method = RequestMethod.POST)
    @ResponseBody
    public Result<Map<String, Object>> batchUploadFile(@RequestParam("files") MultipartFile[] files, @RequestParam("taskId") Long taskId) {
        return R2.ok(taskFileService.batchUploadFile(files, taskId));
    }

    @GetMapping("/getFileList")
    public Result<List<TaskFile>> listFiles(@RequestParam(value = "taskId", required = false) Long taskId) {
        List<TaskFile> files = taskFileService.getAllFiles(taskId);
        return R2.ok(files);
    }

    //    @RequestMapping(value = "batchDownloadFile", method = RequestMethod.GET)
//    public Result<String> batchDownloadFile(@RequestBody List<String> files, HttpServletRequest request, HttpServletResponse response) {
//        return taskFileService.batchDownloadFile(files, request, response) ? R2.setOkMsg("下载成功") : R2.setErrMsg("下载失败");
//    }
    @GetMapping("/download/{fileId}")
    public ResponseEntity<byte[]> downloadFile(@PathVariable String fileId,
                                               @RequestParam(required = false, defaultValue = "false") boolean isPreview) throws IOException {
        // 根据 fileId 获取文件信息
        TaskFile taskFile = taskFileService.getById(fileId);
        if (taskFile == null) {
            throw new RRException("没找到对应文件");
        }

        String fullPath = taskFile.getFilePath() + taskFile.getId() + "." + taskFile.getFileType();
        File file = new File(fullPath);

        if (!file.exists()) {
            throw new RRException("文件不存在");
        }
        System.out.println(URLEncoder.encode(file.getName(), "UTF-8"));
        // 读取文件内容
        InputStream inputStream = new FileInputStream(file);
        byte[] fileContent = toByteArray(inputStream);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Access-Control-Expose-Headers", "Content-Disposition");
        if (isPreview) {
            // 如果是预览模式，设置为在线查看
            String encodedFileName = URLEncoder.encode(taskFile.getFileNameUp(), "UTF-8").replace("+", "%20");
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + taskFile.getFileNameUp() + "\"; filename*=UTF-8''" + encodedFileName);
        } else {
            // 默认为下载模式
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + URLEncoder.encode(file.getName(), "UTF-8") + "\"");
        }
        headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(file.length()));
        headers.setContentType(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM);

        return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
    }

    // 辅助方法：将 InputStream 转换为 byte[]
    private byte[] toByteArray(InputStream input) throws IOException {
        try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[4096];
            int n = 0;
            while (-1 != (n = input.read(buffer))) {
                output.write(buffer, 0, n);
            }
            return output.toByteArray();
        }
    }


    @PostMapping("/deleteFiles")
    public Result<Map<String, Object>> deleteFiles(@RequestBody Map<String, Object> request) {

        // 从请求中获取文件名列表
        List<String> fileIds = (List<String>) request.get("id");
        if (fileIds == null || fileIds.isEmpty()) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("msg", "文件列表为空");
            throw new RRException("删除失败");
        }

        // 记录删除结果：成功删除的文件、文件删除失败的、以及未找到对应记录的文件
        List<String> deletedFiles = new ArrayList<>();
        List<String> failedFiles = new ArrayList<>();
        List<String> notFoundFiles = new ArrayList<>();
        List<TaskFile> taskFiles = taskFileService.listByIds(fileIds);
        for (TaskFile taskFile : taskFiles) {

            if (taskFile != null) {
                boolean fileDeleted = false;
                String path = taskFile.getFilePath() + taskFile.getId() + "." + taskFile.getFileType();
                File file = new File(path);
                try {
                    // 如果文件存在则尝试删除，不存在则认为已删除
                    if (file.exists()) {
                        fileDeleted = file.delete();
                    } else {
                        fileDeleted = true;
                    }
                } catch (Exception e) {
                    fileDeleted = false;
                }
                try {
                    // 无论文件是否成功删除，都删除数据库记录
                    taskFileService.removeBatchByIds(fileIds);
                } catch (Exception e) {
                    // 如果数据库删除失败，则视为整体删除失败
                    fileDeleted = false;
                }
            }

        }

        return R2.ok();
    }

}
